import paho.mqtt.client as mqtt

# MQTT 服务器地址和端口
broker_address = "127.0.0.1"
broker_port = 1883

# 回调函数：当客户端连接到 MQTT 服务器时触发
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("Connected to MQTT broker")
        client.subscribe("topic1")
    else:
        print("Failed to connect, return code %d\n", rc)
a=0
# 回调函数：当接收到订阅主题的消息时触发
def on_message(client, userdata, message):
    print(message.topic)
    global a
    a+=1
    print(message.topic,{str(message.payload.decode('utf-8'))})
    if a%10000==0:
        print(f"Message received on topic {message.topic}: {str(message.payload.decode('utf-8'))}")

# 创建 MQTT 客户端实例
client = mqtt.Client()

# 设置回调函数
client.on_connect = on_connect
client.on_message = on_message

# 连接到 MQTT 服务器
client.connect(broker_address, broker_port)
client.subscribe("test/#")
# 开始循环监听
client.loop_start()

# 持续运行，直到手动中断
try:
    while True:
        pass
except KeyboardInterrupt:
    print("Stopping...")
    client.disconnect()
    client.loop_stop()